from flask import Flask, request, send_file
import os
from testPspSleepV3Demo import run_upload
from sleepPng import generate_png
import glob

app = Flask(__name__)
os.makedirs("./uploaded", exist_ok=True)
os.makedirs("./received_from_server", exist_ok=True)

@app.route("/upload", methods=["POST"])
def upload():
    file = request.files.get("file")
    if not file:
        print("[server] 没有收到文件")
        return {"error":"no file"}, 400

    # 清理 ./uploaded 下的旧 TXT 文件
    for f in glob.glob("./uploaded/*.txt"):
        os.remove(f)
        print(f"[server] 删除旧上传文件: {f}")

    # 保存新的 TXT 文件
    file_path = os.path.join("./uploaded", file.filename)
    file.save(file_path)
    print(f"[server] 文件已保存到 uploaded: {file_path}")

    # 上传到服务器处理，返回最新 TXT 文件路径
    returned_txt = run_upload(file_path)
    if not returned_txt:
        print("[server] run_upload 返回失败")
        return {"error":"server upload failed"}, 500

    # 生成 PNG（只用最新 TXT）
    png_path = generate_png(returned_txt)
    print(f"[server] PNG 生成完成: {png_path}")

    # 返回 PNG 文件给 iOS
    return send_file(png_path, as_attachment=True)

if __name__=="__main__":
    print("[server] Flask 服务器启动")
    app.run(host="0.0.0.0", port=8080, debug=True)
